/*
 * Copyright (C) 2012 Tomas Shestakov. <http://code.google.com/p/jmmo/>
 */

package jmmo.engine.multifacetedactor

import akka.actor.ActorRef

trait ActorChildren extends MultifacetedActor {

  def allChildren: Iterable[ActorRef] = ownChildren ++ alienChildren

  def ownChildren = context.children

  def alienChildren: scala.collection.Set[ActorRef] = childrenSet

  def addAlienChild(child: ActorRef) {
    if (childrenSet(child)) {
//      throw new IllegalArgumentException(this + " already contains child " + child)
    }
    else {
      childrenSet += child
      child ! AddedToParent(self)
      sendEvent(ChildAdded(child))
    }
  }

  def removeAlienChild(child: ActorRef) {
    if (!childrenSet(child)) {
//      throw new IllegalArgumentException(this + " not contains child " + child)
    }
    else {
      childrenSet -= child
      child ! RemovedFromParent(self)
      sendEvent(ChildRemoved(child))
    }
  }

  override def receive = super.receive orElse {
    case AddChildRequest(child) => addAlienChild(child)
    case RemoveChildRequest(child) => removeAlienChild(child)
    case GetChildrenRequest => sender ! GetChildrenResponse(allChildren)
  }

  protected var childrenSet = Set.empty[ActorRef]
}
